import { CanActivate, ExecutionContext, Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { query, Request, Response } from "express";

import { Reflector } from '@nestjs/core'

/**
 * 路由守卫
 * 以拦截请求，判断路由元数据是否允许的用户角色访问
 *  guard  使用  Reflector 反射读取 setMetaData的值 去做判断这边例子是从url 判断有没有admin权限
 */
@Injectable()
export class GuardGuardRole implements CanActivate {
  constructor(private readonly reflector: Reflector) { }
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    console.log('路由守卫...');
    const ctx = context.switchToHttp();
    const request = ctx.getRequest<Request>();

    const admin = this.reflector.get<string[]>('roles', context.getHandler());
    console.log('admin', admin)

    const isHasRole = admin && admin.includes(request.query.roles as string);

    // 验证token的合理性以及根据token做出相应的操作
    if (isHasRole) {
      try {
        // 这里可以添加验证逻辑
        return true;
      } catch (e) {
        throw new HttpException(
          '没有授权访问,',
          HttpStatus.UNAUTHORIZED,
        );
      }
    } else {
      throw new HttpException(
        '没有授权访问,',
        HttpStatus.UNAUTHORIZED,
      );
    }
  };


}
